package tech.ezrealc.fall2023.controller;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import tech.ezrealc.fall2023.exception.AuthenticationFailedException;
import tech.ezrealc.fall2023.model.common.ResponseModel;
import tech.ezrealc.fall2023.model.session.SessionQuery;
import tech.ezrealc.fall2023.model.session.SessionVO;
import tech.ezrealc.fall2023.service.SessionService;

@RestController
@RequestMapping("/api/session")
@CrossOrigin
@Slf4j
public class SessionController {

    @Resource
    private SessionService sessionService;

    @PostMapping
    public ResponseModel authenticate(@RequestBody SessionQuery sessionQuery) throws AuthenticationFailedException {
        SessionVO sessionVO = new SessionVO(sessionService.authenticate(sessionQuery).getToken());
        return ResponseModel.success(sessionVO);
    }

    @ExceptionHandler(AuthenticationFailedException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseModel authenticationFailedExceptionHandler(Exception exception) {
        log.info(exception.getMessage());
        return ResponseModel.failure(exception.getMessage());
    }

    @DeleteMapping
    public ResponseModel deAuthenticate(@RequestHeader("Fall2023-Token") String token) {
        if (!sessionService.deAuthenticate(token)) {
            return ResponseModel.failure("登出失败");
        }
        return ResponseModel.success();
    }

}
